<?php

namespace App\Http\Controllers;

use App\Common\HttpClient;
use App\Common\Logger;
use App\Common\Sql;
use App\Common\Tool;
use Illuminate\Support\Facades\DB;

class Register extends Base
{

    public function logic()
    {
        if (!isset($this->param['user'])) {
            return $this->returnError(1, "手机号参数未输入.");
        } else {
            $user = $this->param['user'];
            if (!preg_match("/^1[34578]\d{9}$/", $user)) {
                return $this->returnError(2, '手机号格式错误');
            }
        }

        if (!isset($this->param['password'])) {
            return $this->returnError(3, "password must be need.");
        } else {
            $password = $this->param['password'];
        }
        $password_reg = '/[a-zA-Z0-9]{4,20}/';
        if (!preg_match($password_reg, $this->param['password'])) {
            return $this->returnError(4, '密码最长为4-20位，包含英文、数字，请重新填写');
        }

        if (!isset($this->param['nick_name'])) {
            return $this->returnError(5, "昵称不能为空");
        } else {
            $nick_name = $this->param['nick_name'];
            $reg       = "/^[0-9a-zA-Z\x{4e00}-\x{9fa5}]+$/u";
            if (preg_match($reg, $nick_name)) {
                $cnt = mb_strwidth($nick_name, "utf-8");
                if ($cnt >= 4 && $cnt <= 14) {
                } else {
                    return $this->returnError(6, "昵称长度2到7个汉字字符,或者4~14个英文数字字符");
                }
            } else {
                return $this->returnError(7, "昵称只支持中文、英文、数字");
            }

        }

        if (!isset($this->param['ua'])) {
            $ua = "";
        } else if (strlen($this->param['ua']) > 20) {
            $ua = substr($this->param['ua'], 0, 20);
        } else {
            $ua = $this->param['ua'];
        }

        $row = DB::table('t_player_info')
            ->where('phone_num', strtolower($this->param['user']))
            ->select(DB::raw('COUNT(*) AS `count`'))
            ->get()->map(function ($value) {
                return (array)$value;
            });
        if ($row[0]['count'] >= 1) {
            return $this->returnError(8, '手机号账户已经存在');
        }

        $new_user = $this->createUser($ua, $user, $password, $nick_name);
        $uid      = Sql::insert('t_player_info', $new_user);
        if ($uid <= 0) {
            Logger::instance()->error(Tool::getUri(), 'insert user error');
            return $this->returnError(9, "查询玩家数据失败");
        }

        $login_ip   = $_SERVER["REMOTE_ADDR"];
        $province   = "未知";
        $city       = "未知";
        $url_prefix = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
        $url        = $url_prefix . $login_ip;
        $client     = new HttpClient();
        $ret        = $client->Get($url);
        if ($ret == false) {
        } else {
            $find = (array)json_decode($ret, true);
            if (!empty($find['ret']) && $find['ret'] == 1) {
                $province = $find["province"];
                $city     = $find["city"];
            }
        }

        Sql::insert('t_login_rec', [
            "login_uid" => $uid,
            'login_type' => 1,
            'login_ip' => $login_ip,
            'login_province' => $province,
            'login_city' => $city
        ]);

        $user_info['uid']          = (int)$uid;
        $user_info['sex']          = (int)$new_user['sex'];
        $user_info['nick_name']    = $new_user['nick_name'];
        $user_info['diamonds']     = $this->get_user_diamonds($uid);
        $user_info['gold']         = $this->get_user_gold($uid);
        $user_info['login_ip']     = $new_user['login_ip'];
        $user_info['skey']         = $new_user['skey'];
        $user_info['login_type']   = 1;
        $user_info['paiwei_score'] = (int)$new_user['paiwei_score'];

        $ret_arr                       = $this->cal_paiwei_rank($user_info['paiwei_score']);
        $user_info['paiwei_rank']      = $ret_arr["paiwei_rank"];
        $user_info['paiwei_rank_name'] = $ret_arr["paiwei_rank_name"];

        return $this->returnData($user_info);
    }


    private function createUser($ua, $phone_num, $password, $nick_name)
    {
        $now                       = date('Y-m-d H:i:s', time());
        $user_info                 = array();
        $user_info["phone_num"]    = $phone_num;
        $user_info["nick_name"]    = $nick_name;
        $user_info["passwd_md5"]   = md5($password);
        $user_info["passwd"]       = $password;
        $user_info["status"]       = 1;        // 0：为封号的, 1:表示账号可用
        $user_info["sex"]          = 0;
        $user_info["ua"]           = $ua;
        $user_info["diamonds"]     = 88;
        $user_info["gold"]         = 15000;
        $user_info["create_time"]  = $now;
        $user_info["update_time"]  = $now;
        $user_info["skey"]         = md5(time());
        $user_info["login_ip"]     = $_SERVER["REMOTE_ADDR"];
        $user_info["paiwei_score"] = 0;
        return $user_info;
    }

    private function cal_paiwei_rank($paiwei_score)
    {
        $row = Sql::select('t_rank_conf', [['min_score', '<=', $paiwei_score], ['max_score', '<', $paiwei_score]]);
        if (count($row) <= 0) {
            Logger::instance()->error(Tool::getUri(), "get paiwei error.\n");
            $rank                     = array();
            $rank['paiwei_rank']      = 0;
            $rank['paiwei_rank_name'] = "无";
            return $rank;
        }
        $rank                     = array();
        $rank['paiwei_rank']      = (int)$row[0]["id"];
        $rank['paiwei_rank_name'] = $row[0]["name"];
        return $rank;
    }
}
